【前端學習】innerText 與 textContent 的差異


Posted by Annie-Chien on 2022-08-21

innerText 和 textContent 好像都可以用來取得元素內的文字,那我到底該用哪一個? 還是其實都沒差(才怪!)。


MDN 的定義

先來看看 MDN 是如何解釋的:

innerText

The innerText property of the HTMLElement interface represents the rendered text content of a node and its descendants.

textContent

The textContent property of the Node interface represents the text content of the node and its descendants.

英文定義看起來還是沒什麼兩樣啊...
幫你畫個重點:兩個都是用來代表 text content (文字內容)沒錯,不過眼尖的你應該有發現 innerText 代表的不單單只是純文字內容,而是 rendered text content(渲染後的文字內容)。

實際測試

首先我們有個 h1 內寫上 Hello world 的文字內容。

<h1 id='test1'>Hello, world</h1>

css 設定text-transform,讓文字內容以全大寫的樣式渲染在畫面上。

#test1{
  text-transform: uppercase;
}

那猜猜看以下的 JS 會印出什麼呢?

const textContent1 = document.querySelector('#test1').textContent;
const innerText1 = document.querySelector('#test1').innerText;

console.log('textContent: ' + textContent1)
console.log('innerText: ' + innerText1)

. . .

答案如下:

  • textContent 會是最初在 html 內打的文字內容
  • innerText 則是實際出現在畫面上全大寫的文字內容

牛刀小試

了解它們的差別後,相信你一定很快就知道以下程式碼的 textContent 和 innerText 分別是什麼了吧😉

<h1 id='test2'>JavaScript <br/>is fun</h1>

附上 codepen 的測試,自己玩玩去找答案吧!

總結

快速用一句話來總結:

textContet 回傳純文字,而 innerText 則會回傳實際呈現在頁面上的樣子。


#javascript







Related Posts

我的第一堂 - JavaScript 02 變數, 判斷式

我的第一堂 - JavaScript 02 變數, 判斷式

給Python一個虛擬的家...還有在開發時為了保護Secret的Safe place...

給Python一個虛擬的家...還有在開發時為了保護Secret的Safe place...

What Type of Laser Engraving Machine Should be Used for Stainless Steel Engraving?

What Type of Laser Engraving Machine Should be Used for Stainless Steel Engraving?


Comments